package com.osfw.dbadminer.service.database.impl;

import com.osfw.dbadminer.domain.database.HintSqlParam;
import com.osfw.dbadminer.domain.database.TableDef;
import com.osfw.dbadminer.entity.connect.DbaConnect;
import com.osfw.dbadminer.mapper.connect.DbaConnectMapper;
import com.osfw.dbadminer.service.database.IDbaDataTableService;
import com.osfw.dbadminer.service.jdbc.JdbcBaseFactory;
import com.osfw.dbadminer.service.jdbc.JdbcBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据表操作 服务层处理
 */
@Slf4j
@Service
public class DbaDataTableServiceImpl implements IDbaDataTableService {
    @Resource
    private DbaConnectMapper connectMapper;

    public Map<String, Object> getAllHintData(HintSqlParam hintSqlParam) {
        DbaConnect connect = connectMapper.selectById(hintSqlParam.getConnectId());
        JdbcBaseService jdbcService = JdbcBaseFactory.createAndInit(connect);
        try {
            return jdbcService.getHintTableColumn(hintSqlParam);
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public List<TableDef> getAllTables(Long connectId, String database) {
        DbaConnect connect = connectMapper.selectById(connectId);
        JdbcBaseService jdbcService = JdbcBaseFactory.createAndInit(connect);
        try {
            return jdbcService.getTableList(database);
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return Collections.EMPTY_LIST;
    }

    public Map<String, List<String>> getStructure(Long connectId, String database, String tableName) throws SQLException {
        Map<String, List<String>> map = new HashMap<>();
        DbaConnect connect = connectMapper.selectById(connectId);
        JdbcBaseService jdbcService = JdbcBaseFactory.createAndInit(connect);
        List<String> allColumns = jdbcService.getAllColumns(database, tableName);
        map.put("column", allColumns);
        List<String> allIndex = jdbcService.getAllIndex(database, tableName);
        map.put("index", allIndex);
        return map;
    }
}
